<template>
  <div class="commodity_param_detail">
    <div class="main">
      <div class="header">
        <div class="title">
          <span>参数名称</span>
          <el-input v-model.trim="para" />
        </div>
        <div class="btn_group">
          <HPlainButton @click="savePara">保存</HPlainButton>
          <HPlainButton type="error" @click="delePara">删除</HPlainButton>
        </div>
      </div>

      <div class="line"></div>

      <div v-loading="loading" class="body" element-loading-text="加载中...">
        <div class="header">
          <div class="btn_group">
            <HPlainButton @click="addList">添加字段</HPlainButton>
            <el-dropdown trigger="click">
              <HButton :disabled="selecttion.length == 0">
                批量操作
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </HButton>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="useAll">
                    <el-icon>
                      <CircleCheck />
                    </el-icon>
                    批量启用
                  </el-dropdown-item>
                  <el-dropdown-item @click="disableAll">
                    <el-icon>
                      <Warning />
                    </el-icon>
                    批量禁用
                  </el-dropdown-item>
                  <el-dropdown-item @click="deleAll">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    批量删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="search">
            <el-input
              v-model.trim="input"
              clearable
              placeholder="关键词搜索"
              style="width: 180px"
              @keyup.enter="getList"
              @clear="getList"
            />
            <h-button type="primary" @click="getList">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </h-button>
          </div>
        </div>
        <div class="table">
          <el-table
            ref="fieldTable"
            border
            stripe
            resizable
            :data="fieldData"
            height="100%"
            @selection-change="handleChange"
          >
            <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
            <el-table-column
              type="index"
              :index="indexMethod"
              label="序号"
              width="50"
              fixed="left"
              :align="'center'"
            />
            <el-table-column show-overflow-tooltip prop="name" label="字段名称" min-width="200" />
            <el-table-column show-overflow-tooltip prop="type" label="字段类型" width="100">
              <template #default="scope">
                <span>
                  {{
                    scope.row.type == 1
                      ? '文本'
                      : scope.row.type == 2
                      ? '多行文本'
                      : scope.row.type == 3
                      ? '单选'
                      : scope.row.type == 4
                      ? '多选'
                      : scope.row.type == 5
                      ? '多图'
                      : scope.row.type == 6
                      ? '附件'
                      : '视频'
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="content" label="字段内容" width="250" />
            <el-table-column show-overflow-tooltip prop="tip" label="提示信息" width="100">
              <template #default="scope">
                <span> {{ scope.row.tip }} </span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
            <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />

            <!--状态-->
            <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
              <template #default="scope">
                <div class="flex_justify_center">
                  <HStatus v-if="!scope.row.status">启用</HStatus>
                  <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
                </div>
              </template>
            </el-table-column>

            <!--操作-->
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="scope">
                <el-space :size="0" :spacer="spacer">
                  <HLink @click="fieldDetail(scope.row)">编辑</HLink>
                  <h-link type="error" @click="onDelClick(scope.row)">删除</h-link>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="pagination"
            :list_total="fieldTotal"
            @size-change="getSizeList"
            @current-change="getNumList"
          />
        </div>

        <!-- 添加/编辑  字段弹窗 -->
        <h-drawer v-model="addDialog" :title="fieldDialogTitle" :loading="fieldLoading" :width="50">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            class="modal_form_content"
            label-position="top"
            inline-message
          >
            <!-- 字段名称 -->
            <el-form-item label="字段名称" prop="name">
              <el-input v-model.trim="form.name" clearable placeholder="请输入名称" />
            </el-form-item>

            <!-- 字段类型 -->
            <el-form-item label="字段类型" prop="type">
              <el-select
                v-model="form.type"
                class="select_item"
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option
                  v-for="item in options1"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>

            <!-- 是否必填 -->
            <el-form-item label="是否必填" prop="required" class="same_line">
              <el-radio-group v-model="form.required">
                <el-radio :value="false" size="small">选填</el-radio>
                <el-radio :value="true" size="small">必填</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 字段状态 -->
            <el-form-item label="字段状态" prop="status" class="same_line">
              <el-radio-group v-model="form.status">
                <el-radio :value="false" size="small">启用</el-radio>
                <el-radio :value="true" size="small">禁用</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 提示信息 -->
            <el-form-item label="提示信息">
              <el-input
                v-model.trim="tip"
                class="item-input"
                clearable
                placeholder="请输入提示信息"
              />
            </el-form-item>

            <div v-if="form.type === 3 || form.type === 4" class="field_content">
              <!-- 字段内容 -->
              <div class="title">
                <div>字段内容</div>
              </div>
              <el-form
                ref="fieldFormRef"
                label-position="left"
                label-width="30"
                :model="fieldForm"
                :rules="rules"
                inline-message
              >
                <el-form-item
                  v-for="(item, index) in fieldForm.items"
                  :key="index"
                  :prop="`items[${index}][val]`"
                  :rules="rules.text"
                  :label="`${index + 1}`"
                >
                  <el-input v-model.trim="item.val" clearable placeholder="请输入字段内容" />
                  <el-space :size="0" :spacer="spacer">
                    <h-link v-if="index === 0" @click="addText">添加</h-link>
                    <HLink
                      v-if="fieldForm.items.length > 1"
                      type="error"
                      @click="handleDele(index, item)"
                      >删除</HLink
                    >
                  </el-space>
                </el-form-item>
              </el-form>
            </div>

            <!-- 上传数量 -->
            <el-form-item
              v-if="form.type === 5 || form.type === 6 || form.type === 7"
              label="上传数量"
              prop="uploadQty"
            >
              <el-input v-model.trim="form.uploadQty" clearable placeholder="请输入数量" />
            </el-form-item>

            <!-- 上传大小 -->
            <el-form-item
              v-if="form.type === 5 || form.type === 6 || form.type === 7"
              label="上传大小"
              prop="uploadSize"
            >
              <el-input v-model.trim="form.uploadSize" clearable placeholder="请输入大小" />
            </el-form-item>
          </el-form>

          <template #footer>
            <HButton is-modal type="primary" @click="saveAddField(formRef, fieldFormRef)"
              >保存</HButton
            >
            <HButton is-modal @click="onModalCancelClick">取消</HButton>
          </template>
        </h-drawer>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
  import type { FormInstance, TableInstance } from 'element-plus'
  import { ref, reactive, onMounted, h } from 'vue'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { useRoute, useRouter } from 'vue-router'
  import {
    paraSave,
    paraFieldList,
    paraFieldSave,
    paraFieldDisable,
    paraFieldDelete,
    paraFieldInfo,
    paraDelete,
  } from '@/api/goodsSet'
  import { Field } from './types'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.setting.goodAttrDetail,
  })

  const onDelClick = (field: Field) => {
    if (fieldTable.value) {
      fieldTable.value.clearSelection()
      fieldTable.value.toggleRowSelection(field, true)
      fieldID.value = field.id
      deleList()
    }
  }

  //列表序号
  const indexMethod = (index: number) => {
    return (index + 1) * 1
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const TagsViewStore = useTagsViewStore()
  const route = useRoute()
  const router = useRouter()
  const para = ref(route.query.name) // 参数名称

  const loading = ref(false)
  const addDialog = ref(false)

  // 表单元素
  const formRef = ref<FormInstance>()
  const fieldFormRef = ref<FormInstance>()

  // 表单数据
  const form = ref({
    name: '', // 字段名称
    required: false, // 是否必填 false-选项 true-可填
    status: false, // 字段状态 false-启用 true-禁用
    type: 1, // 字段类型
    uploadQty: 10,
    uploadSize: 100,
  })

  const fieldForm = reactive({
    items: [
      {
        val: '',
      },
    ],
    itemIDs: [], // 删除的字段内容ID集合
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入字段名称', trigger: ['blur', 'change'] }],
    text: [{ required: true, message: '请输入字段内容', trigger: ['blur', 'change'] }],
    required: [{ required: true, message: '请选择是否必填', trigger: ['blur', 'change'] }],
    status: [{ required: true, message: '请选择字段状态', trigger: ['blur', 'change'] }],
    type: [{ required: true, message: '请选择字段类型', trigger: ['blur', 'change'] }],
    uploadSize: [
      { required: false, message: '请输入最大尺寸', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: ['blur', 'change'],
      },
    ],
    uploadQty: [
      { required: false, message: '请输入上传数量', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: ['blur', 'change'],
      },
    ],
  })

  const onModalCancelClick = () => {
    addDialog.value = false
  }

  const options1 = [
    {
      value: 1,
      label: '文本',
    },
    {
      value: 2,
      label: '多行文本',
    },
    {
      value: 3,
      label: '单选',
    },
    {
      value: 4,
      label: '多选',
    },
    {
      value: 5,
      label: '多图',
    },
    {
      value: 6,
      label: '附件',
    },
    {
      value: 7,
      label: '视频',
    },
  ]

  const input = ref('') // 搜索框
  const pagination = ref() // 分页Dom
  const fieldLoading = ref(false) // 加载loading
  const fieldTotal = ref() // 总数目
  const fieldData = ref([]) // 表格数据
  const fieldTable = ref<TableInstance | null>(null) // 表格Dom
  const fieldDialogTitle = ref('') // 弹窗标题
  const fieldID = ref('') // 字段ID

  const tip = ref('')

  // 获取字段列表数据
  const getList = async () => {
    loading.value = true
    await paraFieldList(getPagingData(pagination.value, input.value), route.params.id).then(
      (res) => {
        fieldData.value = res.data.data.rows
        fieldTotal.value = parseInt(res.data.data.total)
        loading.value = false
      },
    )
  }

  onMounted(() => {
    getList()
  })

  // 保存参数
  const savePara = () => {
    paraSave({
      id: route.params.id,
      name: para.value,
      status: route.query.status,
    }).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      if (res.data.success == true) {
        TagsViewStore.delView(route.path) // 关闭当前页面
        router.go(-1) // 返回列表页面
      }
    })
  }

  // 删除参数
  const delePara = async () => {
    await changeDisable('删除', '参数', paraDelete, [route.params.id], '3', fieldTable.value, '')
  }

  // 获取分页数据
  const getPagingData = (obj, name) => {
    return {
      type: '',
      name: name,
      limit: obj.size,
      page: obj.current,
    }
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 分页改变时
  const getSizeList = () => {
    getList()
  }

  // 页码改变时
  const getNumList = () => {
    getList()
  }

  // 添加字段
  const addList = () => {
    fieldDialogTitle.value = '添加字段'
    form.value.name = ''
    form.value.type = 1
    form.value.status = false
    form.value.required = false
    form.value.uploadSize = 100
    form.value.uploadQty = 10
    tip.value = ''
    fieldForm.items = [
      {
        val: '',
      },
    ]
    addDialog.value = true
  }

  // 编辑字段
  const fieldDetail = async (obj) => {
    fieldDialogTitle.value = '编辑字段'
    fieldLoading.value = true
    fieldID.value = obj.id
    form.value.name = obj.name
    form.value.type = obj.type
    form.value.status = obj.status
    form.value.required = obj.required
    form.value.uploadQty = obj.uploadQty
    form.value.uploadSize = obj.uploadSize
    addDialog.value = true
    await paraFieldInfo(fieldID.value).then((res) => {
      fieldForm.items = res.data.data.row.contentVos || [
        {
          val: '',
        },
      ]
      fieldLoading.value = false
    })
  }

  // 封装保存字段的数据
  const saveField = (title, text, method, dialog, getList) => {
    const data = {
      type: form.value.type,
      contentIds: [],
      contentVos: [],
      name: form.value.name,
      paramId: route.params.id,
      required: form.value.required,
      status: form.value.status,
      tip: tip.value,
      uploadQty: form.value.uploadQty,
      uploadSize: form.value.uploadSize,
    }
    const data2 = {
      id: fieldID.value,
      type: form.value.type,
      contentIds: fieldForm.itemIDs,
      contentVos: fieldForm.items,
      name: form.value.name,
      paramId: route.params.id,
      required: form.value.required,
      status: form.value.status,
      tip: tip.value,
      uploadQty: form.value.uploadQty,
      uploadSize: form.value.uploadSize,
    }
    if (form.value.type === 3 || form.value.type === 4) {
      let tmp = []
      fieldForm.items.forEach((item) => {
        tmp.push({ val: item.val })
      })
      data.contentVos = tmp
      data.contentVos = fieldForm.items
    }
    if (title == text) {
      method(data).then((res) => {
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        if (res.data.success == true) {
          dialog.value = false
          getList()
        }
      })
    } else {
      method(data2).then((res) => {
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        if (res.data.success == true) {
          dialog.value = false
          getList()
        }
      })
    }
  }

  // 保存字段
  const saveAddField = (formEl: FormInstance | undefined, formEl2: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        if (form.value.type === 3 || form.value.type === 4) {
          formEl2.validate((val) => {
            if (val) {
              saveField(fieldDialogTitle.value, '添加字段', paraFieldSave, addDialog, getList)
            }
          })
        } else {
          saveField(fieldDialogTitle.value, '添加字段', paraFieldSave, addDialog, getList)
        }
      } else {
        return
      }
    })
  }

  // 封装修改状态的方法
  const changeDisable = (type, name, method, arr, status, dom, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的${name}`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确定${type}选中的${name}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != '3') {
        // 批量启用/禁用
        await method(arr, { status: status }).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (res.data.success == true) {
            selecttion.value = []
            dom.clearSelection()
            getList()
          }
        })
      } else {
        // 批量删除
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (res.data.success == true) {
            selecttion.value = []
            if (dialog != '') {
              dialog.value = false
            }
            if (name == '参数') {
              TagsViewStore.delView(route.path) // 关闭当前页面
              router.go(-1) // 返回列表页面
            }
            getList()
          }
        })
      }
    })
  }

  // 删除字段
  const deleList = () => {
    changeDisable(
      '删除',
      '字段',
      paraFieldDelete,
      [fieldID.value],
      '3',
      fieldTable.value,
      addDialog,
    )
  }

  // 批量启用
  const useAll = () => {
    changeDisable('启用', '字段', paraFieldDisable, selecttion.value, false, fieldTable.value, '')
  }

  // 批量禁用
  const disableAll = () => {
    changeDisable('禁用', '字段', paraFieldDisable, selecttion.value, true, fieldTable.value, '')
  }

  // 批量删除
  const deleAll = () => {
    changeDisable('删除', '字段', paraFieldDelete, selecttion.value, '3', fieldTable.value, '')
  }

  // 删除字段内容
  const handleDele = (index, obj) => {
    fieldForm.items.splice(index, 1)
    fieldForm.itemIDs.push(obj.id)
  }

  // 新增字段内容
  const addText = () => {
    const tmp = {
      val: '',
    }
    fieldForm.items.push(tmp)
  }
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
